<?php
namespace Home\Controller;
use Home\Controller\BaseController;

require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
C('TOKEN_ON', false);

class ArticleController extends BaseController {
    /**
     * 文章列表
     * @return [type] [description]
     */
    public function index() {
        $title = I('get.title', '', 'trim');
        $map = array();
//        $map['column_id'] = array('in', $this->channelId);

//        $map['deletetime'] = array('exp','is null');
//        $map['state'] = array('neq', -1);

        $map = 'deletetime is null AND state <> -1';
        if($title) {
//            $map['title'] = array("like","%{$title}%");
            $map .= ' AND title like "%' . $title . '%"';
        }


        if(session('is_admin')) {
            $map .= ' AND column_id in (' . implode(',', $this->channelId) . ')';
        } else {
            if(session('is_type') == 0) {
                $map .= ' AND user_id = ' . session('organ_id');
            } elseif(session('is_type') == 1) {
                $map .= ' AND (column_id in (' . implode(',', $this->channelId) . ') OR user_id = ' . session('organ_id') . ')';
            }
        }

        $aModel = M('Article');
        $total = $aModel->alias('ar')
            ->join('__USER_INFO__ u ON u.uid=ar.user_id','left')->where($map)->count();
        $page = new \Think\Page($total,15);
        $page->rollPage = 7;
        $show = $page->show();

        $articleList = $aModel->where($map)
            ->alias('ar')
            ->join('__USER_INFO__ u ON u.uid=ar.user_id','left')
            ->order('create_time DESC')
            ->limit($page->firstRow .',' . $page->listRows)
            ->select();

        foreach($articleList as $k=>$v){

            if($v['author']){
                $a=M('User_info')->field('realname')->where("uid in ({$v['author']})")->select();
                $s=array();
                foreach($a as $kk=>$vv){
                    $s[]=$vv['realname'];
                }
                $articleList[$k]['author']=implode(',',$s);
            }
        }

        $this->assign('channelIds', $this->channelId);
        $this->assign('showpage', $show);
        $this->assign('articleList', $articleList);
        $this->assign('active', '文稿管理');
        $this->display();

    }


    public function verify() {

        $state = I('get.state');
        if(IS_GET) {
            $id = I('get.id');
        } elseif(IS_POST) {
            $id = I('post.id');
        }

        if(empty($id)) {
            $message['status'] = -1;
            $message['msg'] = '选项不能为空';
            $this->ajaxReturn($message);
        } else {
            $id = explode(',', $id);
        }

        $map['id'] = array('in', $id);
        $res = M('Article')->where($map)->save(array(
            'state' => $state,
        ));

        if($res !== false) {
            if($state == 1) {
                $push_act = A('Push');
                $id = (array) $id;
                foreach($id as $val) {
                    $push_act->pushArticle($val);
                }
            }

            $this->success('审核成功');
        } else {
            $this->error('审核失败');
        }
    }

    public function ajaxDelArticle() {
        if(IS_GET) {
            $id = I('get.id');
        } elseif(IS_POST) {
            $id = I('post.id');
            is_array($id) && $id = implode(',', $id);
        }

        if(empty($id)) {
//            $message['status'] = -1;
//            $message['msg'] = '选项不能为空';
            $this->error('选项不能为空');
        }

        $map['id'] = array('in', $id);
        $res = M('Article')->where($map)->save(array(
            'deletetime' => time(),
        ));
        if($res) {
//            $imap['aid'] = array('in', $id);
//            $attach = M('Attachment')->where($imap)->select();
//
//            M('Attachment')->where($imap)->save(array(
//                'aid' => 0,
//            ));
//
//            foreach($attach as $val) {
//                @unlink(UPLOAD_PATH . $val['filepath'] . $val['filename']);
//            }

//            $message['status'] = 1;
//            $message['msg'] = '删除成功';
            $this->success('删除成功');
            exit;
        } else {
//            $message['status'] = -1;
//            $message['msg'] = '删除失败，请重试';
            $this->error('删除失败，请重试');
        }
    }

    public function editArticle($id) {

        if(IS_POST) {

            $dataGet['id'] = I('post.aid', 0);
            $dataGet['title'] = I('post.title', '');
//            $dataGet['content'] = I('post.content', '', 'strip_tags');
            $dataGet['html_content'] = I('post.content', '');
            $dataGet['update_time'] = time();

            I('post.indexpic', '') && $dataGet['indexpic'] = I('post.indexpic', '');

            $articleModel = D('Article');
            if($articleModel->create($dataGet)) {
                $res = $articleModel->save($dataGet);
                if($res) {
                    $this->success('文档修改成功', U('index'));
                } else {
                    $this->error('文档修改失败');
                }
            } else {
                $this->error($articleModel->getError());
            }
        } else {
            $article=M('Article')->alias('ar')
                ->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
                ->find($id);

            $is_admin = session('is_admin');
            $is_type = session('is_type');

//            if($is_type || $is_admin) {
//                if(!in_array($article['column_id'], $this->channelId)) {
//                    $this->error('对不起，您没有权限管理此文稿');
//                }
//            } else {
//                if($article['user_id'] != session('organ_id')) {
//                    $this->error('对不起，您没有权限管理此文稿');
//                }
//            }


            if($is_admin) {
                if(!in_array($article['column_id'], $this->channelId)) {
                    $this->error('对不起，您没有权限管理此文稿');
                }

            } else {
                if($is_type) {
                    if(!in_array($article['column_id'], $this->channelId)) {
                        if($article['user_id'] != session('organ_id')) {
                            $this->error('对不起，您没有权限管理此文稿');
                        }
                    }
                } else {
                    if($article['user_id'] != session('organ_id')) {
                        $this->error('对不起，您没有权限管理此文稿');
                    }
                }
            }

            $nameList=M('UserInfo')->where(array('uid'=>array('in',$article['author'])))->select();

            $article['content'] = $article['html_content'] ? $article['html_content'] : $article['content'];

            foreach ($nameList as $key => $value) {
                $name[]=$value['realname'];
            }
            $article['authorlist']=$name;

            $attach=M('Attachment')->where(array('aid'=>$id,'attachstate'=>1))->select();

            $this->assign('attach',$attach);
            $this->assign('article',$article);

            $putPolicy= [
//                'saveKey'=>'$(x:type)/$(etag)$(ext)',
                'saveKey'=>'article/$(etag)',
                'callbackUrl' => 'http://' . I('server.HTTP_HOST') . '/Home/Push/callback',
                'callbackBody' => '{"fname":"$(fname)", "fsize":"$(fsize)", "mimeType":"$(mimeType)","hash":"$(etag)", "fkey":"$(key)","ext":"$(ext)","avinfo":$(avinfo), "type":"$(x:type)", "desc":$(x:sortDesc), "aid":' . $id . '}'
            ];
            $upAuth = new Auth(C('QINIU_AK'), C('QINIU_SK'));
            $bucket = C('QINIU_VIDEO_BUCKET');
            $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);

            $this->assign('uploadToken', $uploadToken);

            $this->display();
        }

    }

    public function getImageListByAid() {
        $aid = I('get.id');
        if($aid) {
            $list = M('Attachment')->where(array('aid' => $aid))->order('sort asc')->select(); // 'type' => 'image'

            $mess['status'] = 1;
            $mess['message'] = '';
            $mess['data'] = empty($list) ? array() : $list;

        } else {
            $mess['status'] = -1;
            $mess['message'] = '文稿不存在';
        }
        exit(json_encode($mess));
    }


    /**
     * 文章详情页
     */
    public function details($id) {
        if($id) {
            $map['id'] = $id;
            $article=M('Article')->alias('ar')
                ->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
                ->find($id);

            $nameList = M('UserInfo')->where(array('uid'=>array('in',$article['author'])))->select();

            $article['content'] = $article['html_content'] ? $article['html_content'] : $article['content'];
            $article['content'] = htmlspecialchars_decode($article['content']);

            foreach ($nameList as $key => $value) {
                $name[] = $value['realname'];
            }
            $article['authorlist'] = $name;


            if(preg_match_all('/data-videoid="(.*?)"/', $article['content'], $video_matchs)) {
                if(isset($video_matchs[1]) && !empty($video_matchs[1])) {
                    foreach($video_matchs[1] as $key => $id) {
                        $attachment = M('Attachment')->where(array('attachid' => $id))->find();
//                        $temp=explode('.',$attachment['filename']);
//                        $ext = $temp[count($temp) - 1];
//                        if(in_array($ext, array('mp3'))) {
//                            if(preg_match('/http/i', $attachment['filepath'])) {
//                                $article['content'] = preg_replace('/<img(.*?)data\-videoid="' . $id . '"(.*?)>/i','<audio src="' . $attachment['filepath'] . $attachment['filename'] . '" controls="controls"></audio>', $article['content']);
//                            } else {
//                                $article['content'] = preg_replace('/<img(.*?)data\-videoid="' . $id . '"(.*?)>/i','<audio src="' . C('UPLOAD_HOST') . $attachment['filepath'] . $attachment['filename'] . '" controls="controls"></audio>', $article['content']);
//                            }
//                        } elseif(in_array($ext, array('mp4'))) {
//                            if(preg_match('/http/i', $attachment['filepath'])) {
//                                $article['content'] = preg_replace('/<img(.*?)data\-videoid="' . $id . '"(.*?)>/i','<video src="' . $attachment['filepath'] . $attachment['filename'] . '" controls="controls"></video>', $article['content']);
//                            } else {
//                                $article['content'] = preg_replace('/<img(.*?)data\-videoid="' . $id . '"(.*?)>/i','<video src="' . C('UPLOAD_HOST') . $attachment['filepath'] . $attachment['filename'] . '" controls="controls"></video>', $article['content']);
//                            }
//                        }

                        if(in_array($attachment['ext'], array('.mp3',))) {
                            $article['content'] = preg_replace('/<img(.*?)data\-videoid="' . $id . '"(.*?)>/i','<audio src="' . C('QINIU_RESOURCE_HOST') . $attachment['filepath'] . $attachment['filename'] . '" controls="controls"></audio>', $article['content']);
                        } elseif(in_array($attachment['ext'], array('.mp4'))) {
                            $article['content'] = preg_replace('/<img(.*?)data\-videoid="' . $id . '"(.*?)>/i','<video src="' . C('QINIU_RESOURCE_HOST') . $attachment['filepath'] . $attachment['filename'] . '" controls="controls"></video>', $article['content']);
                        }
                    }
                }
            }


            $this->assign('info', $article);
            $this->display();
        } else {
            $this->error('文稿不存在');
        }
    }

    public function showArticle($id){
         $article=M('Article')->alias('ar')
                ->join('__USER_INFO__ ui ON ar.user_id=ui.uid')
                ->find($id);

            $nameList=M('UserInfo')->where(array('uid'=>array('in',$article['author'])))->select();

            $article['content'] = $article['html_content'] ? $article['html_content'] : $article['content'];

            foreach ($nameList as $key => $value) {
                $name[]=$value['realname'];
            }
            $article['authorlist']=$name;

            $attach=M('Attachment')->where(array('aid'=>$id,'attachstate'=>1))->select();

            $this->assign('attach',$attach);
            $this->assign('article',$article);
           /* dump($attach);
            dump($article);*/
            $this->display();        

    }
}